<template>
  <div>
    <bread :second="'商品管理'" :third="'商品列表'"></bread>
    <!--------------------------------- 卡片 --------------------------------------->
    <el-card class="box-card" style="margin-top:15px ">
      <el-alert
        title="添加商品信息"
        :closable="false"
        type="info"
        center
        show-icon
        style="margin-bottom:10px"
      ></el-alert>
      <!-------------------- 步骤条 -------------------------------->
      <el-steps :active="Number(activeName)" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!----------------------- 侧边导航 ------------------------------>
      <el-tabs
        :tab-position="tabPosition"
        style="margin-top:20px;height:100%"
        v-model="activeName"
        :before-leave="beforeLeave"
      >
        <!--=============================== 基本信息 =======================================-->
        <el-tab-pane name="0" label="基本信息">
          <el-form
            :model="goodsForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
            label-position="top"
          >
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <div class="block">
              <!------------------ 级联选择器 -------------------------->
              <div class="demonstration" style="margin-bottom:20px">商品分类</div>
              <el-cascader
                v-model="goodsForm.goods_cat"
                :options="goodsList"
                :props="props"
                @change="handleChange"
                clearable
                style="margin-bottom:20px"
              ></el-cascader>
            </div>
          </el-form>
        </el-tab-pane>
        <!---------------------------------------- 第二页 ---------------------------------------->
        <el-tab-pane name="1" label="商品参数">
          <el-tag
            style="margin:5px"
            v-for="(item,index) in manyList"
            :key="index"
          >{{item.attr_name}}</el-tag>
        </el-tab-pane>
        <!---------------------------------------- 第三页 ---------------------------------------->

        <el-tab-pane name="2" label="商品属性">
          <el-form label-position="top" label-width="80px" :model="goodsForm" :rules="rules">
            <el-form-item v-for="(item, index) in onlyList" :key="index" :label="item.attr_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <!---------------------------------------- 第四页 ---------------------------------------->
        <!--==================== 图片上传 =======================-->
        <el-tab-pane name="3" label="商品图片">
          <el-upload
            class="upload-demo"
            action="http://klxin.cn:8888/api/private/v1/upload"
            :headers="headers"
            :on-success="fileSuccess"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-tab-pane>
        <!---------------------------------------- 第五页 ---------------------------------------->
        <el-tab-pane name="4" label="商品内容">
          =={{goodsForm.goods_introduce}}==
          <quillEditor style="height:300px" v-model="goodsForm.goods_introduce"></quillEditor>

          <el-button type="primary" @click="addGoodsAll" style="margin-top:60px">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!---------------------------------------- 点击图片弹窗 ----------------------------------------->
    <el-dialog title :visible.sync="picDialogFormVisible" class="img-dialog" width="30%">
      <img :src="picSrc" alt />
    </el-dialog>
  </div>
</template>
          
<script>
import { getCategories_api, getCateList_api } from "@/api/login_api.js";
import { addGoodsAll_api } from "@/api/index.js";
//引入富文本包------------------
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
//---------引入loadsh包-----------------------
import _ from "lodash";
export default {
  components: {
    quillEditor //定义富文本组件
  },
  data() {
    return {
      tabPosition: "left",
      activeName: "0",
      goodsForm: {
        goods_cat: [],
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_introduce: "",
        pics: [],
        attrs: []
      },
      //表单校验----------
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 3, max: 50, message: "长度在 3 到 50 个字符", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ]
      },
      //级联选择器------------
      value: [],
      goodsList: [],
      props: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      //商品参数------------
      manyList: [],
      //商品属性--------------
      onlyList: [],
      //图片上传-----定义请求头-------------------
      headers: {
        Authorization: window.sessionStorage.getItem("token")
      }, //图片数组--------
      fileList: [],
      picSrc: "", //预览图片的路径
      //图片预览弹窗
      picDialogFormVisible: false
    };
  },
  //渲染级联器里的数据列表
  created() {
    this.getCateList();
  },
  methods: {
    //////发送sxios请求，获取商品类表数据---------------------------
    async getCateList() {
      const { data: res } = await getCategories_api({ type: 3 });
      // console.log(res, 66666);
      this.goodsList = res.data;
    },
    //级联选择器方法---------------------------
    handleChange() {
      // console.log(this.goodsForm.goods_cat.length,14141414);

      if (this.goodsForm.goods_cat.length !== 3) {
        this.goodsForm.goods_cat.length = [];
      }
    },
    //第一页的内容都填完，才能跳转到下一页-----阻止tab栏切换-----
    //第一页的索引为0
    beforeLeave(activeName) {
      // console.log(activeName,33333);
      //判断第一页的索引  ---第二页是动态属性many的数据---第三页是静态 only数据
      //  tab栏索引为01234，一直往后切换
      if (activeName !== 0) {
        // 判断是否到第二页商品参数,获取动态属性列表
        if (this.goodsForm.goods_cat.length !== 3) {
          this.$message.error("错了哦，请选择分类数据");
          return false;
        }
        this.getActiveName(activeName);
      }
    },
    //把activename1 activName2 抽离出来
    async getActiveName(activeName) {
      if (activeName == 1) {
        const { data: res } = await getCateList_api({
          id: this.catId,
          sel: "many"
        });
        // console.log(res, 888888);
        this.manyList = res.data;
        //遍历res.data attr_id attr_vals
        res.data.forEach(item => {
          var manyObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          };
          //把manyObj 追加到goodsForm里面
          this.goodsForm.attrs.push(manyObj);
        });
        // console.log( this.goodsForm.attrs,'eeeeeee');
      }
      //判断静态属性
      if (activeName == 2) {
        const { data: res } = await getCateList_api({
          id: this.catId,
          sel: "only"
        });
        this.onlyList = res.data;
        res.data.forEach(item => {
          var onlyObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          };

          this.goodsForm.attrs.push(onlyObj);
        });
      }
    },
    //上传图片的方法-----------------------------------------------------------------
    //图片上传成功的方法
    fileSuccess(response, file, fileList) {
      // console.log(response, file, fileList,1111111);
      //把图片数据放到goodsform里面
      this.goodsForm.pics.push({ pic: response.data.tmp_path });
      // console.log(this.goodsForm.pics, 666777)
    },
    //图片预览----------------------------
    handlePreview(file) {
      this.picDialogFormVisible = true;
      this.picSrc = "http://klxin.cn:8888/" + file.response.data.tmp_path;
    },
    //从数组中移除图片的方法
    handleRemove(file, fileList) {
      //  console.log(file,131313131);
      this.goodsForm.pics = this.goodsForm.pics.filter(
        item => item.pic !== file.response.data.tmp_path
      );
      // console.log(this.goodsForm.pics, 12121212);
    },
    //最后一步，添加商品，发送请求--------------------------------------------------
    addGoodsAll() {
      //把goodsForm做深拷贝
      var goodsCopy = _.cloneDeep(this.goodsForm);
      // console.log(goodsCopy, 1515151515);
      //根据接口要求，把goods_cat转成字符串 以为','分割的分类列表
      goodsCopy.goods_cat = goodsCopy.goods_cat.join(",");
      // console.log(goodsCopy, 222222);
      //按钮做二次校验，发送请求
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const { data: res } = await addGoodsAll_api(goodsCopy);
          console.log(res, 6767676);
        } else {
          this.$message.error("添加商品失败！");
          return false;
        }
      });
    }
  },
  //添加计算属性----------------
  computed: {
    catId() {
      if (this.goodsForm.goods_cat.length == 3) {
        return this.goodsForm.goods_cat[2];
      } else {
        return 2050;
      }
    }
  }
};
</script>
<style scoped lang="less">
.el-steps {
  width: 1000px;
  margin-left: 30px;
}
/deep/.el-step__title {
  font-size: 13px;
}
.img-dialog {
  text-align: center;
  img {
    width: 100%;
  }
}
</style>